//import and format psid data
clear all
do "$data/PSID/home_equity/J339225"
do "$data/PSID/home_equity/J339225_formats"

gen uniqid = ER30001*1000 + ER30002 //generation of uniqid identifier variable
duplicates report uniqid //no duplicates!
drop ER30002 ER30000 
ren ER32000 sex
drop sex

//drop variables we don't care about
//loop over variables and drop what we can
ds uniqid, not
foreach var in `r(varlist)'{
	
	//fetch label
	local lab: variable label `var'
	
	//kill sequence/release/interview numbers
	if strpos("`lab'", "SEQUENCE") | strpos("`lab'", "RELEASE") | strpos("`lab'", "INTERVIEW") | strpos("`lab'", "AGE OF") | strpos("`lab'", "WAGE") | strpos("`lab'", "LABOR") {
		drop `var'
		continue
	}
	
	//get year for individual files
	local num = word("`lab'", -1)
	
	//skip variables with labels that i don't like
	if length("`num'")!=2 | "`var'" == "V4373" {
		continue
	}	
	
	if `num'<20{ //2000s variable
		local year = 2000 + `num'
	}
	if `num'>20{ //1900s variable
		local year = 1900 + `num'
	}
	
	****rename according to label contents

	
	//relation to head
	if strpos("`lab'", "RELATION"){
		ren `var' relate_`year'
	}
}


drop *19*
ren S520 home_eq_2001
ren S620 home_eq_2003
ren S720 home_eq_2005
ren S820 home_eq_2007
ren ER46966 home_eq_2009
ren ER52390 home_eq_2011
ren ER58207 home_eq_2013
drop relate_2015 relate_2017


//fill in even years for age, relate
local even `"2002 2004 2006 2008 2010 2012"'
foreach year in `even'{
	local plus = `year' + 1
	gen relate_`year' = relate_`plus' //assume relate did not change in previous year
}

reshape long home_eq_ relate_, i(uniqid) j(year)
keep if relate == 1 | relate == 10 //household heads only
ren home home_eq
compress
drop ER32006 relate_




merge m:1 year using "$data/GDP/gdp_pce_deflator", keep(match) nogen

replace home_eq = (home_eq/deflator) * 100
save "$temp/psid_home_eq", replace

//end of dofile